<template>
  <a-card :bordered="false">
    <h3>话题内容列表</h3>
    <ContentFilter :url="url" ref="filter" :type="4" :extensionVisible.sync="extensionVisible" @onContentExport="onContentExport" @onSearch="onSearch"></ContentFilter>
    <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
      <span slot="userInfor" slot-scope="text, record"> {{ record.userNickname }}/{{ record.phone }}(社区ID：{{ record.communityId }}) </span>
      <span slot="imageVideo" slot-scope="text, record, index">
        <div v-if="record.contentType == 0" class="image-video-wrapper">
          <template v-if="record.pictureVideo">
            <img class="img" v-for="(item, index) in record.pictureVideo.split(',').slice(0, 1)" :src="item" alt="" @click="handleShowImg(index, record.pictureVideo.split(','))" :key="index" />
            <div class="img-num">{{ record.pictureVideo.split(',').length }}张</div>
          </template>
        </div>
        <img v-else class="image-video-wrapper img" @click="handlePreview(record.pictureVideo)" :src="record.cover" alt="" />
      </span>
      <span slot="content" slot-scope="text, record">
        <p style="font-weight: bold;">{{ record.contentTitle }}</p>
        <a-popover :overlayStyle="{ width: '240px', height: 'auto' }">
          <template slot="content">
            <p style="word-break: break-all;">{{ record.bodyContent }}</p>
          </template>
          <span class="remarks">{{ record.bodyContent }}</span>
        </a-popover>
      </span>
      <span v-if="record.communityTopicAssGoodsDtoList.length" class="img-wrapper" slot="productList" slot-scope="text, record, index">
        <div class="img-list" @click="handleShowProductList(record.communityTopicAssGoodsDtoList)">
          <template v-for="(item, index) in record.communityTopicAssGoodsDtoList.slice(0, 3)" >
            <img class="img" v-if="item.image" :src="item.image" alt="" :key="index" />
            <img class="img" v-else src="https://picttype1.jnby.com/community/goods/pl-goods.png" alt="" :key="'place'+index" />
          </template>
        </div>
        <div class="img-text" @click="handleShowProductList(record.communityTopicAssGoodsDtoList)">共{{ record.communityTopicAssGoodsDtoList.length }}件</div>
      </span>
      <span slot="topicName" slot-scope="text, record">
        <a-tag color="#2db7f5" v-if="record.topicName">#{{ record.topicName }}</a-tag>
        <span v-else>/</span>
      </span>
      <span slot="reason" slot-scope="text, record">
        <div style="font-weight: bold;">{{ record.informType }}</div>
        <div style="color: #999;">{{ record.informReason }}</div>
      </span>
      <span slot="action" slot-scope="text, record">
        <a @click="handleDetails(record.id)">详情</a>
        <a-divider type="vertical" />
         <a @click="handleShowExtension(record.id)">推广</a>
          <a-divider type="vertical" />
        <a @click="handleDisable(record.id)">禁用</a>
        <template v-if="record.identityId == 1">
          <a-divider type="vertical" />
          <a @click="handleEdit(record.id)">编辑</a>
        </template>
        <a-popconfirm
          v-if="record.identityId == 1"
          title="确定要删除该内容吗？"
          ok-text="确定"
          cancel-text="暂不"
          @confirm="handleDelet(record.id)"
        >
          <a-divider type="vertical" />
          <a>删除</a>
        </a-popconfirm>
      </span>
    </s-table>
    <ParagraphPic :current="imgCurrent" :visible.sync="imgVisible" :imgs="imgs"></ParagraphPic>
    <PreviewVideo :visible.sync="previewVisible" :videoUrl="videoUrl"></PreviewVideo>
    <DisableModal :visible.sync="disableVisible" :whyList="whyList" @onOk="onOk"></DisableModal>
    <ProductListModal :visible.sync="productVisible" :productList="productList"></ProductListModal>
  </a-card>
</template>
<script>
import { contentPage, contentAddOrUpdate, contentDelete, contentDetails, contentExport } from '@/api/micromall/communityContent'
import { whyPage } from '@/api/micromall/communityUser'
import { STable } from '@/views/box/components'
import ContentFilter from '../../components/ContentFilter'
import ParagraphPic from '../../components/ParagraphPic'
import PreviewVideo from '../../components/PreviewVideo'
import { enabledColumns } from '../contentManagement/contentList.js'
import DisableModal from '../../components/DisableModal'
import ProductListModal from '../../components/ProductListModal'
 import qs from 'qs'
export default {
  components: {
    ContentFilter,
    STable,
    ParagraphPic,
    PreviewVideo,
    DisableModal,
    ProductListModal
  },
  data() {
    return {
      url: '',
      total: 0,
      sort: {},
      pageNo: 1,
      pageSize: 10,
      id: '',
      details: {},
      whyList: [],
      disableVisible: false,
      extensionVisible: false,
      videoUrl: '',
      previewVisible: false,
      productVisible: false,
      imgCurrent: 0,
      imgVisible: false,
      imgs: [],
      productList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      columns: enabledColumns,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {},

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (this.requestFlag()) return
        if (parameter.sortOrder) {
          this.sort = {}
          this.sort[parameter.sortField + 'Sort'] = parameter.sortOrder == 'descend' ? '0' : '1'
        } else {
          delete this.sort[parameter.sortField + 'Sort']
        }
        this.pageNo = parameter.pageNo
        this.pageSize = parameter.pageSize
        const data = {
          status: '0',
          topicId: this.$route.params.id,
          ...this.queryParam,
          current: parameter.pageNo,
          size: parameter.pageSize,
          ...this.sort
        }
        return contentPage(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            this.total = total
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  created() {
  },
  activated() {
    this.getWhyPage()
  },
  computed: {},
  mounted() {},
  watch: {
    $route(to, from) {
      const whiteList = [
        '/micromall/community/contentManagement/details/',
       '/micromall/community/contentManagement/addOrEditOfficialContent', 
       '/micromall/community/contentManagement/materialList']
      const currentPathBase = '/micromall/community/contentManagement/topicContentList'
      const currentPath = this.$route.path
      if (this.checkRoute(from.path, whiteList) && to.path.includes(currentPathBase)) {
        this.$refs.table.refresh() // 刷新当前列表（记录上次页码）
      } else {
        if (currentPath.includes(currentPathBase)) {
          this.$refs.table.refresh(true) // 刷新当前页面
        }
      }
    }
  },
  methods: {
    requestFlag() {
      const currentPathBase = '/micromall/community/contentManagement/topicContentList'
      const currentPath = this.$route.path
      if (!currentPath.includes(currentPathBase)) return true
      return false
    },

    handleShowExtension(id) {
      this.extensionVisible = true
      this.url = `/packages/wm-cloud-jnbycommunity/contentDetail/index?id=${id}`
    },

    // 禁用原因
    getWhyPage() {
      // 3内容禁用原因
      const data = {
        type: 3,
        status: 0
      }
      whyPage(data).then(res => {
        if (res.code === 200) {
          this.whyList = res.data.records
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 禁用
    handleDisable(id) {
      this.id = id
      this.disableVisible = true
    },

    // 禁用弹窗确认
    onOk(v) {
      const { note, why } = v
      const data = {
        id: this.id,
        status: '1',
        disableWhy: why.map(e => e.id).join(','),
        disableNote: note,
        whyName: why.map(e => e.whyName).join(',')
      }
      contentAddOrUpdate(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 话题内容导出
    onContentExport() {
      if (!this.total) {
        this.$message.error('暂无数据！')
        return
      }
      const data = {
        status: '0',
        topicId: this.$route.params.id,
        ...this.queryParam,
        ...this.sort
      }
      window.location.href = contentExport + `?${qs.stringify(this.filterFields(data))}&current=${this.pageNo}&size=${this.pageSize}`
    },

    // 展示关联商品
    handleShowProductList(productList) {
      this.productList = productList
      this.productVisible = true
    },

    // 删除
    handleDelet(id) {
      contentDelete({ id }).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg)
        }
      })
    },


    // 预览视频
    handlePreview(url) {
      this.videoUrl = url
      this.previewVisible = true
    },

    checkRoute(fromPath, routeArr) {
      for (let i = 0; i < routeArr.length; i++) {
        if (fromPath.includes(routeArr[i])) {
          return true
        }
      }
      return false
    },

    //搭配内商品
    handleShowCurrentProductList(list) {
      this.productList = list
      this.productVisible = true
    },

    // 编辑
    handleEdit(id) {
      this.$router.push(`/micromall/community/contentManagement/addOrEditOfficialContent/${id}`)
    },

    // 详情
    handleDetails(id) {
      this.$router.push(`/micromall/community/contentManagement/details/${id}`)
    },

    // 查看大图
    handleShowImg(index, productImgList) {
      this.imgCurrent = index
      this.imgVisible = true
      this.imgs = productImgList
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    },

    filterFields(values) {
      const formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] && values[i].length) {
          if (i === 'time') {
            formValue.startTime = values[i][0]
            formValue.endTime = values[i][1]
          } else if (i === 'auditTime') {
            formValue.auditStartTime = values[i][0]
            formValue.auditEndTime = values[i][1]
          } else if(i === 'releaseTime'){
            formValue.releaseStartTime = values[i][0]
            formValue.releaseEndTime = values[i][1]
          } else {
            formValue[i] = values[i]
          }
        }
      })
      return formValue
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img-wrapper {
  display: flex;

  .img-list {
    display: flex;
  }

  .img-text {
    line-height: 60px;
    color: #999;
  }
}

.img {
  display: block;
  margin: 0 2px;
  width: 60px;
  height: 60px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}

.remarks {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  word-break: break-all; /* 追加这一行代码 */
  /* autoprefixer: off */
  -webkit-box-orient: vertical;
  /* autoprefixer: on */
}
.product {
  display: flex;
  overflow: hidden;
  .img {
    margin: 0;
  }
  .product-name {
    flex: 1;
    margin-left: 5px;
    width: 80px;
    text-align: left;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    word-break: break-all; /* 追加这一行代码 */
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
  }
}
.product-list {
  .product-item {
    line-height: 18px;
    text-align: left;
  }

  .product-num {
    cursor: pointer;
    text-align: left;
  }
}
.content-record {
  position: absolute;
  right: 0;
  top: 15px;
}
.image-video-wrapper {
  position: relative;
  width: 60px;
  height: 60px;
  margin: 0 auto;
  .img-num {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    line-height: 18px;
    text-align: center;
    font-size: 12px;
    color: #fff;
    background: rgba(0, 0, 0, 0.5);
  }
}
</style>
